<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/8/7
 * Time: 15:54
 */

namespace App\Api\Admin\Controllers;

use App\Http\Controllers\Controller;
use App\Exceptions\ApiException;
use App\Services\Admin;
use Illuminate\Support\Facades\Cache;
use App\Models\AdminUser;
use App\Models\Admin\Role;
use App\Models\AdminMenu;

class LoginController extends Controller
{
    /**
     * 登录
     * @return array
     * @throws ApiException
     */
    public function login()
    {
        $username = IT('username', true, '请输入用户名');
        $password = IT('password', true, '请输入密码');
        $user = AdminUser::where(['username'=>$username,'is_delete'=>0])->first();
        if (!$user){
            return json_error('用户名不存在或用户名错误');
        }
        $md5password = md5($password);
        if ($user && $md5password.$user->encrypt != $user->password.$user->encrypt) {
               return json_error('密码不正确');
        }
        $Role = Role::where('id',$user->role_id)->first();
        if($Role->permissions == '*'){
            $menu_list = AdminMenu::where('parent_id',0)->select('id','title as name','uri as path')->orderBy('order','ASC')->get()->toArray();
            foreach ($menu_list as &$item){
                $item['children'] = AdminMenu::where('parent_id',$item['id'])->select('id','title as name','order','parent_id','uri as path')->orderBy('order','ASC')->get()->toArray();
            }
        } else {
            $permissions_list = explode(',', $Role['permissions']);
            $menu_list = AdminMenu::where('parent_id',0)->select('id','title as name','uri as path')->orderBy('order','ASC')->get()->toArray();
            foreach($menu_list as $key => &$top_menu) {
                $top_menu['children'] = AdminMenu::where('parent_id',$top_menu['id'])->select('id','title as name','order','parent_id','uri as path')->orderBy('order','ASC')->get()->toArray();
                foreach($top_menu['children'] as $k => &$son_menu) {
                    if(!AdminMenu::where(['parent_id' => $son_menu['id']])->whereIn('id', $permissions_list)->first()) {
                        unset($top_menu['children'][$k]);
                    }
                }
                if(empty($top_menu['children'])) {
                    unset($menu_list[$key]);
                    continue;
                }
                $top_menu['children'] = array_values($top_menu['children']);
            }
            $menu_list = array_values($menu_list);
        }
        
        $user = array_merge($user->toArray(), Admin::getPermission($user->role_id));
        $token = md5(date('Ymd') . uniqid());
        $res = Cache::put($token, $user, 1440);
        return json_success('ok', ['token' => $token, 'name' => $user['name'],'role_id'=>$user['role_id'], 'role' => $user['role'],'id'=>$user['id'], 'menu'=>$menu_list]);
    }

    /**
     * @desc 发送手机验证码
     * @return array
     * @throws \Exception
     */
    public function registerSms(){
        $expire = config('app.sms_expire');    //短信存活时间，单位分钟
        $mobile = IT('mobile', true, '手机号不能为空');
        if(!preg_match("/^\\d{11}$/",$mobile)){
            return json_error('手机号必须为11位数字');
        }
        //该手机请求时间存活为60秒
        $is_request = cache('bind_sms_'.$mobile,false);
        if($is_request){
            return json_error('请勿频繁请求，请耐心等待60秒');
        }
        $authCode = create_smscode($mobile,$expire);
        $res = send_msg($mobile, $authCode);
        if($res){
            return json_success('验证码发送成功');
        }
        return json_success('验证码发送失败');
    }
    /**
     * @return array
     * 验证码检测
     */
    public  function check_smscode() {
        $mobile = IT('mobile',true,'请输入手机号码');
        $smscode= IT('smscode',true,'请输入验证码');
        if(check_smscode($mobile,$smscode) === true){
            return json_success('ok');
        }else{
            return json_error('验证码， 不正确');
        }
    }

    /**
     *忘记密码修改
     */
    public function ForgetPpassword(){
        $mobile = IT('mobile', true, '请输入手机号码');
        $smscode = IT('smscode', true, '请输入验证码');
        $password= IT('password',true,'请输入密码');
        $confirm_password = IT('confirm_password', true, '请输入确认密码');

        if(trim($password) !== trim($confirm_password)) {
            return json_error('密码与确认密码不一致');
        }
        $is_record = AdminUser::where(['mobile'=> $mobile, 'is_delete' => 0])->first(['id']);
        if(!$is_record) {
            return json_error('手机号不存在');
        }
        if(check_smscode($mobile,$smscode) !== true) {
            return json_error('验证码不正确');
        }

        $data = [
            'password' => md5(trim($password)),
            'encrypt' => str_random(8),
            'updated_at' => time2date()
        ];

        $rs = AdminUser::where(['mobile' => $mobile, 'is_delete' => 0])->update($data);
        if ($rs) {
            return json_success('ok');
        } else {
            return json_error('重置密码失败');
        }
    }


}